package zhihuilan.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import zhihuilan.common.aspect.SpringContextHolder;
import zhihuilan.entity.MyConfig;
import zhihuilan.entity.tools.baidu.BaiduAddressComponent;
import zhihuilan.entity.tools.baidu.BaiduReverseGeocoding;
import zhihuilan.service.MyConfigService;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaiduMapUtils {
    private static MyConfigService myConfigService = SpringContextHolder.getBean(MyConfigService.class);

    private final static String AK = "baidumapkey_server";

    /**
     * 百度地图：经纬>地址
     */
    public static JSONObject lnglat2address(String lng, String lat) {
        MyConfig myConfig = myConfigService.selectByName(AK);
        String ak = myConfig.getValue();
        String url = "http://api.map.baidu.com/reverse_geocoding/v3/?location=" + lat + "," + lng + "&ak=" + ak + "&output=json&extensions_poi=1";
        String address_data = HttpUtils.sendGet(url);
        JSONObject jsonObject = JSONObject.parseObject(address_data);
//    dump($json_data);
        if (jsonObject.get("status").toString().equals("1")) {
            return null;
        }
        return jsonObject.getJSONObject("result");
    }

    /**
     * 百度地图：地址>经纬
     *
     * @param address
     */
    public static String addr2lnglat(String address) throws UnsupportedEncodingException {
        MyConfig myConfig = myConfigService.selectByName(AK);
        String ak = myConfig.getValue();
        String newdata = URLEncoder.encode(address, "UTF-8");
        String url = "http://api.map.baidu.com/geocoding/v3/?address=" + newdata + "&output=json&ak=" + ak;
        String address_data = HttpUtils.sendGet(url);
        JSONObject jsonObject = JSONObject.parseObject(address_data);
        if (!jsonObject.getString("status").equals("1")) {
            return "";
        }
        return JSONObject.parseObject(jsonObject.getString("result")).getString("location");
    }


    /**
     * 百度地图：经纬>地址省市县
     *
     * @param
     */
    public static Object lnglat2addr(String lng, String lat, String field, String pos) {
        MyConfig myConfig = myConfigService.selectByName(AK);
        String ak = myConfig.getValue();
        String url = "http://api.map.baidu.com/reverse_geocoding/v3/?location=" + lat + "," + lng + "&ak=" + ak + "&output=json&extensions_poi=1";
        String address_data = HttpUtils.sendGet(url);
        JSONObject jsonObject = JSONObject.parseObject(address_data);
        if (jsonObject.getString("status").equals("1")) {
            return null;
        }
        if (pos != null) {
            List pois = (List) JSONObject.parseObject(jsonObject.getString("result")).get("pois");
            List list = new ArrayList();
            for (int i = 0; i < pois.size(); i++) {
                Map map = (Map) pois.get(i);
                Map map1 = new HashMap();
                map1.put("address", map.get("addr"));
                map1.put("name", map.get("name"));
                map1.put("lng", JSONObject.parseObject(map.get("point").toString()).get("x"));
                map1.put("lat", JSONObject.parseObject(map.get("point").toString()).get("y"));
                list.add(map1);

            }
            return list;
        }
        JSONObject address = JSONObject.parseObject(jsonObject.getString("result")).getJSONObject("addressComponent");
        if (field != null) {
            if (field.equals("array")) {
                String poiname = address.getString("street");
                List poiRegions = (List) JSONObject.parseObject(jsonObject.getString("result")).get("poiRegions");
                if (!poiRegions.isEmpty()) {
                    Map map = (Map) poiRegions.get(0);
                    poiname = map.get("name").toString();
                }
                address.put("poiname", poiname);
                return (address);
            } else {
                String district = jsonObject.getJSONObject("result").getJSONObject("addressComponent").getString("district");
                // cookie( "district_name", district, 30 * 24 * 3600 );
                String result = jsonObject.getJSONObject("result").getJSONObject("addressComponent").getString(field).trim();
                result = result.replaceFirst("市", "");
                return result;
            }
        } else {
            return address.getString("province") + "," + address.getString("city") + "," + address.getString("district");
        }
    }

    /**
     * 百度地图：经纬>地址省市县
     *
     * @param
     */
    public static String lnglat2addr(String lng, String lat) {
        MyConfig myConfig = myConfigService.selectByName(AK);
        String url = "http://api.map.baidu.com/reverse_geocoding/v3/?location=" + lat + "," + lng + "&ak=" + myConfig.getValue() + "&output=json&extensions_poi=1";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        BaiduReverseGeocoding baiduReverseGeocoding = JSON.parseObject(result, BaiduReverseGeocoding.class);
        if (baiduReverseGeocoding.getStatus() == 0) {
            BaiduAddressComponent addressComponent = baiduReverseGeocoding.getResult().getAddressComponent();
            String region = "";
            if (!ObjectUtils.isEmpty(addressComponent)) {
                region = addressComponent.getProvince() + "," + addressComponent.getCity() + "," + addressComponent.getDistrict();
            }
            return region;
        } else {
            return null;
        }
    }

    /**
     * 百度地图：传入经纬度、获取经纬度对应的地理位置信息；
     *
     * @param lng lat 经纬度
     * @return 百度地图经纬度逆地理地址解析返回结果类；
     */
    public static BaiduReverseGeocoding getBaiduAddressInfo(String lng, String lat) {
        MyConfig myConfig = myConfigService.selectByName(AK);
        String url = "http://api.map.baidu.com/reverse_geocoding/v3/?location=" + lat + "," + lng + "&ak=" + myConfig.getValue() + "&output=json&extensions_poi=1";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        BaiduReverseGeocoding baiduReverseGeocoding = JSON.parseObject(result, BaiduReverseGeocoding.class);
        if (baiduReverseGeocoding.getStatus() == 0) {
            return baiduReverseGeocoding;
        } else {
            return null;
        }
    }


    public static void AipImageProcess(String appId,String apiKey,String secretKey,String url) {
//        // 初始化一个AipImageProcess
//        AipImageProcess client = new AipImageProcess(appId, apiKey, secretKey);
//
//        // 可选：设置网络连接参数
//        client.setConnectionTimeoutInMillis(2000);
//        client.setSocketTimeoutInMillis(60000);
//
//        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
////        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
////        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理
//
//        // 调用接口
//        String path = "test.jpg";
//        JSONObject res = client.imageProcess(path, new HashMap<String, String>());
//        System.out.println(res.toString(2));

    }

}
